Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
    return fmt;
};

(function ($) {
    $.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

    var isBusy = false;
    var tempUrl = '';
    /**
     * post请求
     * @param url 请求url
     * @param data 请求body
     * @param successFun 成功后执行的方法
     */
    $.restClient = function (url, data, successFun) {
        if (isBusy && (url == tempUrl)) {
            return;
        }
        tempUrl = url;
        isBusy = true;
        $.ajax({
            type: 'POST',
            contentType: 'application/json;charset=UTF-8',
            url: url,
            data: data || '{}',
            beforeSend: function (xhr) {
                var token = '';
                if (token) {
                    xhr.setRequestHeader('X-AUTH-TOKEN', token);
                }
            },
            complete: function (xhr, ts) {
                isBusy = false;
                tempUrl = '';
            },
            success: function (data) {
                if (data && data.status == -1 && data.message) {
                    $.alert(data.message, function () {
                        var imgCaptcha = $('#imgCaptcha');
                        if (imgCaptcha) {
                            imgCaptcha.attr('src', '/lego/captcha.jpg?time=' + (+new Date()));
                        }
                    });
                } else if (successFun) {
                    successFun(data);
                }
            }
        });
    };

    /**
     * 将str格式的字符串转化为json字符串
     * @param data   key=value&key=value
     */
    $.toJsonStr = function (data) {
        var result = '{';
        var params = data.split('&');
        $.each(params, function (index, element) {
            if (element) {
                var param = element.split('=');
                if (param && (param.length === 2) && param[1]) {
                    result += '"' + param[0] + '":"' + param[1] + '",'
                }
            }
        });
        if (result.charAt(result.length - 1) === ',') {
            result = result.substr(0, result.length - 1);
        }
        result += '}';
        // 解决中文乱码
        result = decodeURIComponent(result);
        return result;
    };
})(jQuery);

// 业务相关的
(function ($) {
    $.appId = 'wx435d4b1a0a06fc7e';
    $.agentId = 0;

    $.howUsePrizeCode = 'http://mp.weixin.qq.com/s/7CXEb2ZDkY2fGRwf9FPJ6A';
    $.howGetPrize = 'http://mp.weixin.qq.com/s/IjJNAbO9UKLEdRxBbLybvQ';
    $.gotoErrorPage = function (container) {
        container.load('/mobile/error.html', function () {
            container.show();
        });
    };
    /**
     * 微信js-sdk权限验证
     *
     * @param successFun    成功的回调
     * @param failFun   失败的回调
     */
    $.wxJsApiConfig = function (successFun, failFun) {
        $.restClient('/wxJs/config', $.toJsonStr('corpId=' + $.appId + '&agentId=' + $.agentId + '&url=' + encodeURIComponent(location.href.split('#')[0])), function (data) {
            //通过config接口注入权限验证配置
            wx.config({
                debug: false,
                appId: data.corpId,
                timestamp: data.timestamp,
                nonceStr: data.nonceStr,
                signature: data.signature,
                jsApiList: ['hideAllNonBaseMenuItem', 'closeWindow']
            });
            wx.ready(function () {
                wx.hideAllNonBaseMenuItem();
                if (successFun) {
                    successFun();
                }
            });
            wx.error(function (res) {
                if (failFun) {
                    failFun();
                } else {
                    $.gotoErrorPage($('body'));
                }
            });
        });
    };
})(jQuery);